var subject=$("#main")
$('html, body').animate({scrollTop: $(document).height()}, 50)
$("#footer_chat").on("input",".inputBox",function(){
	var iptval=$(this).val();
	if(iptval){
		$(".more").hide();
		$(".send").css("display","inline-block");
	}else{
		$(".send").hide();
		$(".more").css("display","inline-block");
	}
})

//$("#footer").on("click",".expression",function(){
//	$(".issuePictures").hide();
//	$(".issueExpressions").show();
//})
$("#footer_chat").on("click",".inputBox",function(){
	$(".issuePictures").hide();
	$(".issueExpressions").hide();
	$("#main").find("ul").css("margin-bottom","1.3rem")
})
$("#footer_chat").on("click",".more",function(){
	$(".issuePictures").show();
	$(".issueExpressions").hide();
	$("#main").find("ul").css("margin-bottom",$("#footer_chat").height()+"px")
	$('html, body').animate({scrollTop: $(document).height()}, 50)
})
$("#subject").on("click",function(){
	$(".issuePictures").hide();
	$(".issueExpressions").hide();
	$("#main").find("ul").css("margin-bottom","1.3rem")
})

	$('.expression').qqFace({

		id : 'facebox',
		assign:'inputBox',
		path:'arclist/'	//表情存放的路径
	});
function replace_em(str){
	str = str.replace(/\</g,'&lt;');
	str = str.replace(/\>/g,'&gt;');
	str = str.replace(/\n/g,'<br/>');
	str = str.replace(/\[em_([0-9]*)\]/g,'<img src="arclist/$1.gif" border="0" />');
	return str;
}

$("#hearder").on("click","img",function(){
	history.go(-1)
})







//图片显示  
 function showPics(url,name){          
         //根据路径读取到文件   
         console.log(url)
            plus.io.resolveLocalFileSystemURL(url,function(entry){  
                entry.file( function(file){  
                    var fileReader = new plus.io.FileReader();  
                    fileReader.readAsDataURL(file);  
                    fileReader.onloadend = function(e) {  
                          var picUrl = e.target.result.toString(); 
                          console.log(picUrl)
                          var picIndex = $("#picIndex").val();  
                          var mine = '{"username":"{$uinfo.username}","avatar":"{$uinfo.avatar}","id":"{$uinfo.id}","mine":true,"content":"img['+picUrl+']"}';
		                  var to = '{"username":"buhaoxiao","id":'+toid+',"avatar":"/uploads/20180416/23bc86fe78be6fe32e56f14263383c79.jpg","sign":"前端就是这么牛","name":"buhaoxiao","type":"friend"}';
		                  var login_data = '{"type":"chatMessage","data":{"mine":'+mine+', "to":'+to+'}}';
		                  socket.send( login_data );
		                  var timer=Date.parse(new Date())
		                  var newMine = '{"username":"{$uinfo.username}","avatar":"{$uinfo.avatar}","id":"{$uinfo.id}","timestamp":"'+timer+'","mine":true,"content":"img['+picUrl+']"}';
		                  for(var i=0;i<historyData.data.length;i++){
				                if(historyData.data[i].id==toid){
				                	historyData.data[i].arrData.push(JSON.parse(newMine));
				                }
			                }
                  		storage.setItem("historyData",JSON.stringify(historyData));
                        var nowIndex = parseInt(picIndex)+1;  
                        $("#picIndex").val(nowIndex);  
                        var html = '';  
                        var html='<li class="issue clear">'
			                      +'<div class="issueChatImg"></div>'
			                      +'<div class="newTimer">'+timestampToTime(new Date())+'         <!-- <span>{$uinfo.username}</span> --></div>'
			                      +'<img  class="figureImg figureImg_r" src="img/product.png">'
			                      +'<img class="chat_img" src="'+picUrl+'" data-preview-src="" data-preview-group="1">'
			                      +'</li>';                      
                        $(".chatList").append(html);   
                  }  
               });  
          });   
       } 


        //压缩图片    
       function compressImage(url,filename){    
           var name="_doc/upload/"+filename;  
           plus.zip.compressImage({    
                   src:url,//src: (String 类型 )压缩转换原始图片的路径    
                   dst:name,//压缩转换目标图片的路径    
                   quality:40,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100    
                   overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件    
               },    
               function(zip) {  
                   //页面显示图片  
                   showPics(zip.target,name);  
               },function(error) {    
                   plus.nativeUI.toast("压缩图片失败，请稍候再试");    
           });    
       }   
        
        //调用手机摄像头并拍照  
       function getImage() {    
           var cmr = plus.camera.getCamera();    
           cmr.captureImage(function(p) {    
               plus.io.resolveLocalFileSystemURL(p, function(entry) {    
                   compressImage(entry.toLocalURL(),entry.name);    
               }, function(e) {    
                   plus.nativeUI.toast("读取拍照文件错误：" + e.message);    
               });    
           }, function(e) {    
           }, {    
               filter: 'image'   
           });    
       }  
       //从相册选择照片  
       function galleryImgs() {    
            plus.gallery.pick(function(e) {    
                var name = e.substr(e.lastIndexOf('/') + 1);  
               compressImage(e,name);  
            }, function(e) {    
            }, {    
                filter: "image"    
            });    
        }  
         
       //点击事件，弹出选择摄像头和相册的选项  
        function showActionSheet() {    
            var bts = [{    
                title: "拍照"    
            }, {    
                title: "从相册选择"    
            }];    
            plus.nativeUI.actionSheet({    
                    cancel: "取消",    
                    buttons: bts    
                },    
                function(e) {    
                    if (e.index == 1) {    
                        getImage();    
                    } else if (e.index == 2) {    
                        galleryImgs();    
                    }    
                }    
            );    
        }   


var kehu_id=getUrlParam("id")
var page=0;
slideDown("#main", 61, function (e) {
    var that = this;
   var  historyData =JSON.parse(storage.getItem('historyData'));
   if(historyData.data.length!=0) {
       if (typeof historyData.data[0].timestamp != "undefined") {
           var timestamp = (historyData.data[0].timestamp) / 1000;
       } else if (typeof historyData.data[0].timer != "undefined") {
           var timestamp = (new Date(historyData.data[0].timer).getTime) / 1000;
       } else {
           var timestamp = 0;
       }
       var timestamp = 0;
   }else
       {
           var timestamp = 0;
       }
       page++;
        var data={};
          data['timestamp']=timestamp;
          data['kehu_id']=kehu_id;
          data['page']=page;
          getchatlog(data);
    that.back.call();
});




function getchatlog(data)
{
    $.ajax({
        type: "post",
        url: "http://admin.chinlingcloud.com/admin/chatlog/getkehistory",
        data: data,
        async: false,
        timeout : 20000,
        beforeSend: function (xhr) {
            //loadData1(defaultData1)
            showDiv()
            //xhr.setRequestHeader("token", tokenk);
        },
        success: function (data) {
            hiddenDiv()
            
            data=JSON.parse(data)
            console.log(data);
            if(data.length==0){
            	taostr("没有更多了！",1000)
            }
            for(var i=0;i<data.length;i++){
                if(data[i].fromid!=kehu_id){
                    var img= data[i].content.substring(0,4);
                    var img1= data[i].content.substring(data[i].content.length-1);
                    var content;
                    if(img=="img[" && img1=="]" ){
                        content=' <img class="chat_img" src="'+data[i].content.substring(4,data[i].content.length-1)+'" data-preview-src="" data-preview-group="1">'
                    }else {
                        content='<p>'+replace_em(data[i].content)+'</p>'
                    }
                    var str='<li class="issue clear">'
                        +'<div class="issueChatImg"></div>'
                        +'<div class="newTimer">'+timestampToTime(data[i].timeline)+'</div>'
                        +'<img  class="figureImg figureImg_r" src="'+data[i].fromavatar+'">'
                        +content
                        +'</li>';
                    $(".chatList").prepend(str)
                    $(".inputBox").val("");
                    $(".send").hide();
                    $(".more").css("display","inline-block");
                }else{
                    var img= data[i].content.substring(0,4);
                    var img1= data[i].content.substring(data[i].content.length-1);
                    var timer=timestampToTime(data[i].timeline)
                    var content;
                    if(img=="img[" && img1=="]" ){
                        content=' <img class="chat_img" src="'+data[i].content.substring(4,data[i].content.length-1)+'" data-preview-src="" data-preview-group="1">'
                    }else {
                        content='<p>'+replace_em(data[i].content)+'</p>'
                    }
                    var str='<li class="received clear">'
                        +'<div class="receivedChatImg"></div>'
                        +'<div class="newTimer">'+timer+'</div>'
                        +'<img  class="figureImg figureImg_l" src="'+data[i].fromavatar+'">'
                        +content
                        +'</li>';
                    $(".chatList").prepend(str);
                }
            }
        },
        complete: function () {
        },
    });
}



mui.previewImage();